package com.swordget.dao.impl;

import com.alibaba.druid.pool.DruidDataSource;
import com.swordget.commons.JdbcUtil;
import com.swordget.dao.HandlerLogDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @Author: David
 * @Date: Created in 17:30 2020/4/17
 * @Description: 数据服务dao 实现
 * @Modified By:
 * @Version: 0.0.1
 */
@Repository
public class HandlerLogDaoImp implements HandlerLogDao {

    private JdbcUtil jdbcUtil;
    private DruidDataSource dataSource;

    /**
     * HandlerLogDaoImp log
     */
    private final static Logger LOG = LoggerFactory.getLogger(HandlerLogDaoImp.class);

    @Autowired
    public HandlerLogDaoImp(JdbcUtil jdbcUtil, DruidDataSource dataSource) {
        this.jdbcUtil = jdbcUtil;
        this.dataSource = dataSource;
    }

    @Override
    public String addUploadLog(String serialNo, String fileName, String filePath, String loginId, String createDate, String createTime) {
        String command = String.format("INSERT INTO UPLOAD_LOG(SERIALNO, FILENAME, FILEPATH, " +
                "MAKEUSER, CREATEDATE, CREATETIME) VALUES('%s', '%s', '%s', '%s', '%s', '%s')",
                serialNo, fileName, filePath, loginId, createDate, createTime);
        if (jdbcUtil.execute(command)) {
            return serialNo;
        }
        return null;
    }

    @Override
    public String findUploadFilePath(String fileId) {
        String command = String.format("SELECT FILEPATH FROM UPLOAD_LOG WHERE SERIALNO  = '%s'", fileId);
        try (Connection conn = dataSource.getConnection();
             Statement statement = conn.createStatement();
             ResultSet resultSet = statement.executeQuery(command)) {
            if (resultSet.next()) {
                return resultSet.getString(1);
            }
        } catch (SQLException e) {
            LOG.error("程序执行过程中出现异常", e);
        }
        return null;
    }
}
